Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: How Many Numbers Are Smaller Than the Current Number

Problem Statement

Given an integer array nums, return the answer array where answer[i] is the count of smaller elements than nums[i].

Examples

  • Example 1:

    • Input: nums = [5, 3, 6, 1, 4]
    • Expected Output: [3, 1, 4, 0, 2]
    • Justification: For the first element (5), there are three elements (3,1 and 4) that are smaller. For the second element (3), there is one element (1) smaller than it. For (6), there are four elements smaller than it. For (1), there are no smaller elements, and for (4), there are two elements (3 and 1) that are smaller.
  • Example 2:

    • Input: nums = [6, 6, 6, 6, 6]
    • Expected Output: [0, 0, 0, 0, 0]
    • Justification: Each element is equal to the others, so there are no elements smaller than any given element.
  • Example 3:

    • Input: nums = [1, 2, 3, 4, 5]
    • Expected Output: [0, 1, 2, 3, 4]
    • Justification: This is a strictly increasing sequence. Each number has all the previous numbers in the sequence smaller than itself.

Solution

To solve this problem, we can use a brute force approach by comparing each element with every other element to count how many numbers are smaller than it. However, a more efficient approach involves first sorting the array and using the sorted positions to determine how many elements are smaller. By sorting, we map each element to its position in the sorted order, which directly correlates to the number of elements smaller than it, considering duplicates.

This approach is effective because sorting gives us an ordered sequence where the position of each element naturally indicates the count of numbers less than it, except for handling duplicates. To handle duplicates effectively, we maintain a mapping of each unique number to its index in the sorted array. This ensures that each unique number gets the lowest possible rank, which corresponds to the count of numbers less than it.

Step-by-step Algorithm

  1. Sort the Input Array: Create a sorted copy of the input array nums. This sorted array will help us identify the relative position of each number, which indirectly tells us how many numbers are smaller than each element.

  2. Initialize an Empty HashMap (index_map): This hashmap will store each unique number from the sorted array as keys, and their first occurrence index as values. This index represents the count of unique numbers that are smaller than the key number.

  3. Populate the HashMap: Iterate over the sorted array sorted_nums. For each number num in sorted_nums, if num is not already a key in index_map, add num as a key with its index i as its value. If num is already a key, skip to the next number. This step ensures each number is mapped to the number of unique elements that are smaller than it.

  4. Generate the Result Array: Iterate over the original array nums, and for each element num, use index_map to find the count of numbers smaller than num. Place this count in the corresponding position of a new result array.

  5. Return the Result Array: The result array, now filled with the counts of smaller numbers for each element in nums, is returned as the final output.

Algorithm Walkthrough

  • Input Array: [5, 3, 6, 1, 4]

  • Step 1: Create a copy of the array and sort it.

    • Sorted Array: [1, 3, 4, 5, 6]
  • Step 2: Initialize an empty hashmap index_map.

  • Step 3: Populate the hashmap.

    • Iteration 1: num = 1, index_map becomes {1: 0}
    • Iteration 2: num = 3, index_map becomes {1: 0, 3: 1}
    • Iteration 3: num = 4, index_map becomes {1: 0, 3: 1, 4: 2}
    • Iteration 4: num = 5, index_map becomes {1: 0, 3: 1, 4: 2, 5: 3}
    • Iteration 5: num = 6, index_map becomes {1: 0, 3: 1, 4: 2, 5: 3, 6: 4}
  • Step 4: Generate the result array by iterating over the original array and using index_map.

    • Original Array Element 5: 3 numbers are smaller (index_map[5]), so first element in result array is 3.
    • Original Array Element 3: 1 number is smaller (index_map[3]), so second element in result array is 1.
    • Original Array Element 6: 4 numbers are smaller (index_map[6]), so third element in result array is 4.
    • Original Array Element 1: 0 numbers are smaller (index_map[1]), so fourth element in result array is 0.
    • Original Array Element 4: 2 numbers are smaller (index_map[4]), so fifth element in result array is 2.
  • Step 5: The final result array is [3, 1, 4, 0, 2], which is returned as the output.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  1. Sorting: The initial sorting of the array takes time, where (n) is the number of elements in the input array.
  2. Mapping: Creating the map from the sorted array takes time since we iterate through the sorted array once.
  3. Building the Result Array: Iterating through the original array to form the result array, using the map for lookup, also takes time.

Therefore, the overall time complexity of the algorithm is due to the sorting step, which dominates the linear iterations.

Space Complexity

  1. Sorted Array: We create a sorted copy of the input array, which takes space.
  2. Mapping/Indexing Structure: The space taken by the map or dictionary is in the worst case when all elements are unique.
  3. Result Array: The output array also takes space.

Thus, the total space complexity is , considering the additional structures used besides the input.

How Many Numbers Are Smaller Than the Current Number (easy)
Binary Tree Paths (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity